import { useEffect, useLayoutEffect, useState } from "react";
import reactLogo from "./assets/react.svg";
import { invoke } from "@tauri-apps/api/core";
import { open, save } from '@tauri-apps/plugin-dialog';
import { create, truncate } from '@tauri-apps/plugin-fs';
import styled from 'styled-components';
import { PlusSquareOutlined, DeploymentUnitOutlined } from '@ant-design/icons';
import { Button, Dropdown, Drawer } from "antd";
import type { MenuProps } from 'antd';
import { type } from "@tauri-apps/plugin-os";

import {
  DefaultSpinner,
  ErrorScreen,
  LoadingScreen,
  Tldraw,
  Editor,
  defaultEditorAssetUrls,
  createTLStore,
  getSnapshot,
  exportToBlob,
  loadSnapshot,
  DefaultQuickActions,
  DefaultQuickActionsContent,
  TldrawUiButton,
  TldrawUiIcon,
  DefaultSharePanel,
  throttle
} from 'tldraw'
import 'tldraw/tldraw.css';

import FONTS from '../../assets/fonts/ComicMono.woff';

import { MakeRealPanel, FileTabs, FileItem } from '../../components';
import * as utils from '../../utils'

import { MenuBar } from './components';

function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onloadend = () => {
      // 读取完成后，返回结果
      resolve(reader.result);
    };

    reader.onerror = () => {
      // 读取出错
      reject(new Error('Failed to convert blob to base64'));
    };

    // 读取 Blob 数据为 Data URL（Base64）
    reader.readAsDataURL(blob);
  });
}

export function ViewerPage() {

  const [filePath, setFilePath] = useState<FileItem | null>(null);

  const [editor, setEditor] = useState<Editor | null>(null);

  const [currentFile, setCurrentFile] = useState<string | null>(null);

  const [loading, setLoading] = useState<boolean>(false);

  const [makeRealOpen, setMakeRealOpen] = useState(false);

  const [inputs, setInputs] = useState<Array<{ url: string }>>([]);

  useLayoutEffect(() => {
    if (!editor || loading) return;

    if (!filePath) {
      const newStore = createTLStore();
      loadSnapshot(editor.store, newStore.getStoreSnapshot());
      return;
    }
    let fileName = filePath.path;
    if (fileName && fileName != null) {
      setLoading(true);
      setMakeRealOpen(false);
      //读取文件的内容
      utils.readTextFromFile(fileName, {}).then((content) => {
        try {
          if (content && content.length > 0) {
            loadSnapshot(editor.store, JSON.parse(content));
          } else {
            const newStore = createTLStore();
            loadSnapshot(editor.store, newStore.getStoreSnapshot());
          }
        } catch (err) {
          //获取失败
          console.log(err);
        }
        setLoading(false);
      });
    }
  }, [editor, filePath]);


  useEffect(() => {
    if (!editor) return;

    const saveCallback = throttle(() => {
      //保存
      console.log('保存........');
      let snapshot = editor.getSnapshot();
      filePath && utils.saveText(filePath.path, JSON.stringify(snapshot));
    }, 5000);
    //另存为
    // utils.saveText2File(JSON.stringify(snapshot), { name: '', extensions: ["json"] });
    const unlisten = editor.store.listen(
      (update) => {
        // console.log('update', update)
        //
        saveCallback();
      },
      { scope: 'document', source: 'user' }
    );

    return () => {
      if (!editor) return;
      unlisten && unlisten();
    }
  }, [editor, filePath]);


  // assetUrls={{
  //   fonts: {
  //     draw: '/fonts/ComicMono.woff',
  //   }
  // }}

  return (
    <Container>
      <HeaderContainer data-tauri-drag-region>
        <TabsContainer>
          <FileTabs
            category={'tldraw'}
            tabBarExtraContent={(callback) => {
              return {
                left: <CreateButtonContainer>
                  <Dropdown menu={{
                    items: [
                      {
                        label: <CreateMenusContainer onClick={async () => {
                          let file = await save({
                            title: '',
                            filters: [{
                              name: 'rrg01',
                              extensions: ['rrg01']
                            }],
                            canCreateDirectories: true
                          }) as any;

                          if (!file) {
                            return;
                          }
                          console.log(file);
                          let createResult = await create(file);
                          //打开文件
                          callback({
                            name: file,
                            path: file,
                          });
                        }}>新建空白</CreateMenusContainer>,
                        key: '0',
                      },
                      {
                        type: 'divider',
                      },
                      {
                        label: <CreateMenusContainer onClick={async () => {
                          let file = await save({
                            title: '',
                            filters: [{
                              name: 'rrg01',
                              extensions: ['rrg01']
                            }],
                            canCreateDirectories: true
                          }) as any;

                          if (!file || !editor) {
                            return;
                          }
                          console.log(file);
                          let createResult = await create(file);
                          let snapshot = editor.getSnapshot();
                          filePath && await utils.saveText(file, JSON.stringify(snapshot));
                          callback({
                            name: file,
                            path: file,
                          });
                        }}>复制并新建</CreateMenusContainer>,
                        key: '1',
                      },
                      {
                        type: 'divider',
                      },
                      {
                        label: <CreateMenusContainer>新建架构图</CreateMenusContainer>,
                        key: '2',
                        disabled: true,
                      }
                    ] as MenuProps['items']
                  }} trigger={['click']}>
                    <PlusSquareOutlined />
                  </Dropdown>
                </CreateButtonContainer>
              }
            }}
            onAdd={async () => {
              const file: any = await open({
                multiple: false,
                directory: false,
                filters: [{
                  name: 'rrg01',
                  extensions: ['rrg01']
                }],
              }) as any;
              if (!file) {
                return null;
              }
              console.log(file, file.path);
              return {
                name: file,
                path: file,
              };
            }}
            onChange={async (item) => {
              console.log(item, '----');
              setFilePath(item);
            }}></FileTabs>
        </TabsContainer>
        <EmptyBox data-tauri-drag-region style={{ minWidth: type() !== 'macos' ? '100px' : '4px' }}></EmptyBox>
      </HeaderContainer>
      <WidgetContainer>
        <div style={{ position: 'fixed', inset: 0, top: '46px', left: '60px' }}>
          <Tldraw
            components={{
              QuickActions: () => {
                return <>
                  <DefaultQuickActions>
                    {DefaultQuickActionsContent()}
                    <div>
                      <TldrawUiButton type={'icon'}>
                        <DeploymentUnitOutlined
                          style={{
                            fontSize: '20px',
                            color: '#E02020',
                          }}
                          onClick={async () => {
                            let pages = editor.getPages();
                            let inputsArray = [];
                            for (let i = 0; i < pages.length; i++) {
                              // const shapeIds = editor.getCurrentPageShapeIds();
                              const shapeIds = editor.getPageShapeIds(pages[i]);
                              if (shapeIds.size === 0) return;

                              const blob = await exportToBlob({
                                editor,
                                ids: [...shapeIds],
                                format: 'png',
                                opts: { background: true },
                              })
                              var imageUrl = await blobToBase64(blob);
                              inputsArray.push({ url: imageUrl });
                            }
                            setInputs(inputsArray);
                            setMakeRealOpen(true);
                          }} />
                      </TldrawUiButton>
                    </div>
                  </DefaultQuickActions>
                </>
              },
              SharePanel: () => {
                return (<DefaultSharePanel></DefaultSharePanel>)
              }
            }}
            onMount={(editorObj) => {
              setEditor(editorObj);
            }}>
          </Tldraw>
          <Drawer
            title="生成"
            onClose={() => {
              setMakeRealOpen(false);
            }}
            width={'calc(100% - 50px)'}
            getContainer={false}
            maskClosable={false}
            open={makeRealOpen}>
            <MakeRealPanel preview={{}} prompts={{
              inputs
            }}></MakeRealPanel>
          </Drawer>
        </div>
      </WidgetContainer>
    </Container >
  );
}

export default ViewerPage;

const Container = styled.div`
  width: 100%;
  height: 100%;
`;

const HeaderContainer = styled.div`
    height: 46px;
    width: 100%;
    display: flex;
    flex-direction: row;
    background-color: #dddddd;
    border-bottom: 1px solid #d9d9d9;
`;

const TabsContainer = styled.div`
    margin-top: 6px;
    height: 40px;
    border-bottom: 1px solid #d9d9d9;
    overflow: hidden;

`;

const WidgetContainer = styled.div`
    width: 100%;
    flex:1;
    padding: 0;
    overflow: hidden;
`;

const CreateButtonContainer = styled.div`
    width: 40px;
    height: 40px;
    font-size: 20px;
    background-color: #ffffff;
    color:red;
    display: flex;
    align-items: center;
    justify-content: center;
`;

const CreateMenusContainer = styled.div`
    width: 100px;
`;

const EmptyBox = styled.div`
    height: 100%;
    overflow: hidden;
    flex: 1;
`;

const EmptyData = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #FFF;
`;

